﻿using HJMinimally.Utility.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;

namespace HJMinimally.Minio.WebApi.Filter
{
    public class GlobalAuthFilter : IActionFilter
    {
        //private readonly IUserService _userService;
        //public GlobalAuthFilter(IUserService userService)
        //{
        //    _userService = userService;
        //}
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //var description =
            //    (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;
            ////匿名标识
            //var authorize = description.MethodInfo.GetCustomAttribute(typeof(AllowAnonymousAttribute));
            //if (authorize != null)
            //{
            //    return;
            //}
            //if (!_userService.CheckLogin())
            //{
            //    context.HttpContext.Response.StatusCode = 401;
            //    context.Result = new JsonResult(new ResParameter
            //    {
            //        code = ResponseCode.nologin,
            //        info = "认证失败，请提供认证信息",
            //        data = new object { }
            //    });
            //}
            //实体[Required(ErrorMessage = "缺少参数")]验证
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                string error = string.Empty;
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        error = state.Errors.First().ErrorMessage;
                        break;
                    }
                }
                context.Result = new JsonResult(new ResParameter
                {
                    code = ResponseCode.exception,
                    info = error,
                    data = new object { }
                });
            }
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            return;
        }
    }
}
